package com.cw.service.impl;

import com.cw.entity.Menu;
import com.cw.mapper.MenuMapper;
import com.cw.service.MenuService;
import com.cw.utils.JwtUtils;
import com.cw.utils.R;
import com.cw.utils.WebUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: MySyetem
 * @description:
 * @author: 张庆恒
 * @create: 2021-08-28 19:11
 **/
@Service
public class MenuServiceImpl implements MenuService {

    @Resource
    private MenuMapper mapper;

    @Override
    public R getMenu() {
        HttpServletRequest request = WebUtil.getRequest();
        String token = request.getHeader("token");
        Integer roleid = JwtUtils.getClaimByName(token, "roleid").asInt();
        List<Menu> menus = mapper.getMenu(roleid);
        //一级菜单（父菜单）
        ArrayList<Menu> parentMenu = new ArrayList<>();
        for (Menu menu : menus) {
            if (menu.getMpid() == 0) {
                parentMenu.add(menu);
            }
        }
        //二级菜单
        for (Menu parent : parentMenu) {
            ArrayList<Menu> childMenu = new ArrayList<>();
            for (Menu child : menus) {
                if (parent.getMid().equals(child.getMpid())) {
                    childMenu.add(child);
                }
            }
            parent.setChildMenu(childMenu);
        }
        return new R(1,"查询菜单成功",parentMenu.size(),parentMenu);
    }
}
